import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    goodList: [
      {
        name: '诸葛亮',
        price: 1000,
        num: 1,
        checked: false
      },
      {
        name: '蔡文姬',
        price: 1500,
        num: 1,
        checked: false
      },
      {
        name: '妲己',
        price: 2000,
        num: 1,
        checked: false
      },
      {
        name: '鲁班',
        price: 2200,
        num: 1,
        checked: false
      }
    ],
    newItem: {
      name: '',
      price: 0,
      num: 1,
      checked: false
    }
  },
  mutations: {
    isChecked (state, payload) {
      // console.log(e[0].target.checked)
      state.goodList[payload[1]].checked = payload[0].target.checked
    },
    addNum (state, payload) {
      state.goodList[payload].num++
    },
    subNum (state, payload) {
      if (state.goodList[payload].num <= 1) {
        return
      }
      state.goodList[payload].num--
    },
    del (state, payload) {
      state.goodList.splice(payload, 1)
    },
    addItem (state, payload) {
      // console.log(payload)
      // state.newItem.name = payload[0]
      // state.newItem.price = payload[1]
      state.goodList.push(payload)
    }
  },
  actions: {
  },
  getters: {
    totalPrice (state) {
      return state.goodList.reduce((sum, item) => {
        if (item.checked) {
          sum += item.price * item.num
        }
        console.log(sum)
        return sum
      }, 0)
    }
  }
})
